package com.atguigu.lease.web.app.interceptor;

import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.context.LoginUserThreadLocal;
import com.atguigu.lease.common.exception.MyBusinessException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName AuthenticationInterceptor
 * @Author heartFade
 * @Date 2025-05-06 9:24
 * @Version 1.0
 * @Description TODO
 **/
@Configuration
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access_token");
        if(!StringUtils.hasText(token))
        {
            throw new MyBusinessException(ResultCodeEnum.TOKEN_EXPIRED);
        }
        Claims claims = JWTUtil.parseToken(token);
        Long id = claims.get("id", Long.class);
        String userName = claims.get("userName", String.class);
        LoginUserContext loginUserContext = new LoginUserContext(id, userName);
        LoginUserThreadLocal.setLoginUserContext(loginUserContext);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       LoginUserThreadLocal.removeLoginUserContext();
    }
}
